package com.hankol.material

import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.bean.download.ShowUIUtils
import com.baselibrary.db.DBManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.GlideUtils
import com.baselibrary.utils.HKUtils
import com.baselibrary.utils.SpUtils
import com.hankol.material.adapter.MaterialCatalogueAdapter
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.LevelOneBean
import com.hankol.material.databinding.ActivityContentlistBinding
import com.hankol.material.fragment.MaterialControlContentFragment
import com.hankol.material.viewmodel.MaterialContentViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author: 关忆北丶
 * @time: 2021/10/15 11:19
 * @description: 筛选界面
 */
@Route(path = ActivityRouter.MATERIAL.MATERIAL_CONTENT_LIST)
class MaterialFilterActivity : BaseActivity() {
    private lateinit var mViewModel: MaterialContentViewModel
    private lateinit var dataBinding: ActivityContentlistBinding
    private var matericalControlContentFragment: MaterialControlContentFragment? = null
    private lateinit var mCatalogueSecondAdapter: MaterialCatalogueAdapter//二级
    private lateinit var mCatalogueTertiaryAdapter: MaterialCatalogueAdapter//三级
    private lateinit var mCatalogueLevelAdapter: MaterialCatalogueAdapter//四级
    private var type: Int = 0
    private var mLevelOneBean: LevelOneBean? = null
    private var mSecondLevelOneBean: LevelOneBean? = null
    private var mTertiaryLevelOneBean: LevelOneBean? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_contentlist
    }

    override fun onResume() {
        super.onResume()
        showDownloadStatus()
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        mViewModel = getActivityViewModelProvider(this).get(MaterialContentViewModel::class.java)
        dataBinding = getDataBinding<ActivityContentlistBinding>()


        mViewModel.screenList.observe(this, Observer {
            when (type) {
                0 -> {
                    //二级目录
                    if (it.isNotEmpty()) {
                        mCatalogueSecondAdapter.setNewData(mViewModel.chanageData(it))
                        dataBinding.rvCatalogueSecond.visibility = View.VISIBLE
                    } else {
                        dataBinding.rvCatalogueSecond.visibility = View.GONE
                        dataBinding.rvCatalogueTertiary.visibility = View.GONE
                        dataBinding.rvCatalogueLevel.visibility = View.GONE
                    }
                    hideLoadingDialog()

                }
                1 -> {
                    //三级目录
                    if (it.isNotEmpty()) {
                        mCatalogueTertiaryAdapter.setNewData(mViewModel.chanageData(it))
                        dataBinding.rvCatalogueTertiary.visibility = View.VISIBLE
                    } else {
                        dataBinding.rvCatalogueTertiary.visibility = View.GONE
                        dataBinding.rvCatalogueLevel.visibility = View.GONE
                    }
                    hideLoadingDialog()
                }
                2 -> {
                    //四级目录
                    if (it.isNotEmpty()) {
                        mCatalogueLevelAdapter.setNewData(mViewModel.chanageData(it))
                        dataBinding.rvCatalogueLevel.visibility = View.VISIBLE
                    }
                    hideLoadingDialog()
                }
            }

        })
        if (intent.extras != null && intent.extras!!.containsKey(MaterialConstants.FOLDER_SCREEN)) {
            mLevelOneBean = intent.extras!!.getParcelable(MaterialConstants.FOLDER_SCREEN)
            mLevelOneBean?.let {
                showLoadingDialog()
                dataBinding.tvContentListTitle.text = it.title
                mViewModel.reqMateriaScreenlList(it.id)
                matericalControlContentFragment = MaterialControlContentFragment.newInstance(mViewModel.loadScreenBean(it.id), dataBinding.appBarLayout, false, this)
                matericalControlContentFragment?.let {
                    supportFragmentManager.beginTransaction().add(R.id.fragment_list, it).commitAllowingStateLoss()
                }
            }
        } else {
            matericalControlContentFragment = MaterialControlContentFragment.newInstance(mViewModel.loadScreenBean(0), dataBinding.appBarLayout, false, this)
            matericalControlContentFragment?.let {
                supportFragmentManager.beginTransaction().add(R.id.fragment_list, it).commitAllowingStateLoss()
            }
        }

        mCatalogueSecondAdapter = MaterialCatalogueAdapter()
        mCatalogueTertiaryAdapter = MaterialCatalogueAdapter()
        mCatalogueLevelAdapter = MaterialCatalogueAdapter()

        dataBinding.rvCatalogueSecond.adapter = mCatalogueSecondAdapter
        dataBinding.rvCatalogueTertiary.adapter = mCatalogueTertiaryAdapter
        dataBinding.rvCatalogueLevel.adapter = mCatalogueLevelAdapter

        initListener()


    }

    private fun initListener() {
        mCatalogueSecondAdapter.setOnItemClickListener { adapter, view, position ->
            mCatalogueSecondAdapter.upSelected(position)
            if (position == 0) {
                dataBinding.rvCatalogueTertiary.visibility = View.GONE
                dataBinding.rvCatalogueLevel.visibility = View.GONE
                mLevelOneBean?.let {
                    matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(it.id))
                }
            } else {
                type = 1
                mSecondLevelOneBean = adapter.data[position] as LevelOneBean
                showLoadingDialog()
                mViewModel.reqMateriaScreenlList(mSecondLevelOneBean!!.id)
                matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(mSecondLevelOneBean!!.id))
            }

        }

        mCatalogueTertiaryAdapter.setOnItemClickListener { adapter, view, position ->
            mCatalogueTertiaryAdapter.upSelected(position)
            if (position == 0) {
                dataBinding.rvCatalogueLevel.visibility = View.GONE
                mSecondLevelOneBean?.let {
                    matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(it.id))
                }
            } else {
                type = 2
                mTertiaryLevelOneBean = adapter.data[position] as LevelOneBean
                showLoadingDialog()
                mViewModel.reqMateriaScreenlList(mTertiaryLevelOneBean!!.id)
                matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(mTertiaryLevelOneBean!!.id))

            }
        }

        mCatalogueLevelAdapter.setOnItemClickListener { adapter, view, position ->
            mCatalogueLevelAdapter.upSelected(position)
            if (position == 0) {
                mTertiaryLevelOneBean?.let {
                    matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(it.id))
                }
            } else {
                val mLevelOneBean = adapter.data[position] as LevelOneBean
                showLoadingDialog()
                matericalControlContentFragment?.handlerData(mViewModel.loadScreenBean(mLevelOneBean.id))

            }
        }

        dataBinding.llContentListBack.setOnClickListener { finish() }
        //跳转下载
        dataBinding.flDownload.setOnClickListener {
            if (!HKUtils.isFastClick()) return@setOnClickListener
            ActivityRouter.startActivity(ActivityRouter.MATERIAL.MATERIAL_DOWNLOAD_MAIN)
        }
        dataBinding.llContentListSearch.setOnClickListener {
            if (!HKUtils.isFastClick()) return@setOnClickListener
            ActivityRouter.startActivity(ActivityRouter.MATERIAL.SEARCH)
        }
    }

    val userIds: Int by lazy { SpUtils.getInstance().userId }

    //显示 下载中的动图 或者 静态图
    private fun showDownloadStatus() {
        val downloadList = DBManager.getInstance().getDownloadList(userIds, false)
        val list = mutableListOf<DownloadInfo>()
        for (info in downloadList) {
            if ((info.downloadStatus.equals(DownloadInfo.DOWNLOAD) || info.downloadStatus.equals(DownloadInfo.DOWNLOAD_PAUSE) || info.downloadStatus.equals(DownloadInfo.DOWNLOAD_WAIT)))
                list.add(info)
        }
        if (list.size > 0) {
            dataBinding.tvDownloadRedCnt.visibility = View.VISIBLE
            dataBinding.tvDownloadRedCnt.text = "${ShowUIUtils.showFormatCnt(list.size)}"
            GlideUtils.loadGif(this, R.drawable.ic_top_downloading, dataBinding.imgDownload)
        } else {
            dataBinding.tvDownloadRedCnt.visibility = View.GONE
            GlideUtils.loadImg(this, R.drawable.ic_top_download, dataBinding.imgDownload)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            showDownloadStatus()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgid_start_download || messageBus.codeType == MessageBus.msgId_del_material_file) {//下载完成或者删除下载的文件
            showDownloadStatus()
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}
